<template>
  <div class="app-container">
    <div class="filter-container" id="filter-container-TmptTimerLog">

      <!--<el-date-picker
          v-model="listQuery.startTime"
          align="right"
          type="date"
          placeholder="startTime"
          :picker-options="pickerOptionsSingleDate"
          class="filter-item"
          clearable
      />

      <el-date-picker
          v-model="listQuery.endTime"
          align="right"
          type="date"
          placeholder="endTime"
          :picker-options="pickerOptionsSingleDate"
          class="filter-item"
          clearable
      />

      <el-input
          v-model="listQuery.tmptTimerId"
          size="small"
          placeholder="tmptTimerId"
          style="width: 200px; "
          class="filter-item"
          @keyup.enter.native="handleFilter"
          clearable
      />-->
      <!--<el-button :loading="queryLoading" class="filter-item" size="small" type="primary" plain icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>-->
      <!--<el-button :loading="downloadLoading" class="filter-item" size="small" type="primary" plain icon="el-icon-download" @click="handleDownload">
        导出报表
      </el-button>
      <el-button v-show="hasPermission(['tmptTimerLog:create'])" class="filter-item" size="small" type="primary" plain icon="el-icon-plus" @click="handleCreate">
        添加
      </el-button>-->
    </div>

    <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        fit
        highlight-current-row
        :show-summary="false"
        :summary-method="getSummaries"
        style="width: 100%;"
        :height="tableHeight"
        @sort-change="sortChange"
        @row-click="handleRowClick"
    >
      <!-- 行展开，显示的详细信息 -->
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="ID" >
                  <span>{{ props.row.id }}</span>
                </el-form-item>
                <el-form-item label="startTime" >
                  <span>{{ props.row.startTime }}</span>
                </el-form-item>
                <el-form-item label="endTime" >
                  <span>{{ props.row.endTime }}</span>
                </el-form-item>
                <el-form-item label="result" >
                  <span>{{ props.row.result }}</span>
                </el-form-item>
                <el-form-item label="tmptTimerId" >
                  <span>{{ props.row.tmptTimerId }}</span>
                </el-form-item>
                <el-form-item label="删除标志" >
                  <span>{{ props.row.deleteflag }}</span>
                </el-form-item>
                <el-form-item label="创建日期" >
                  <span>{{ props.row.createdate }}</span>
                </el-form-item>
                <el-form-item label="修改日期" >
                  <span>{{ props.row.modifydate }}</span>
                </el-form-item>
                <el-form-item label="创建人" >
                  <span>{{ props.row.createman }}</span>
                </el-form-item>
                <el-form-item label="修改人" >
                  <span>{{ props.row.modifyman }}</span>
                </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column
        label="ID"
        prop="id"
        align="center"
        min-width="30"
        :fixed="false">
        <template slot-scope="{row}">
              <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="时间段"
        prop="startTime"
        align="center"
        min-width="60"
        :fixed="false">
        <template slot-scope="{row}">
              <span>{{ row.startTime }}</span>
              <br/>
              <span>{{ row.endTime }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="运行结果"
        prop="result"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
              <el-input v-if="row.edit" v-model="row.result" class="edit-input" size="mini" />
              <span v-else>{{ row.result|shortMsg }}</span>
        </template>
      </el-table-column>

      <!--<el-table-column
        label="tmptTimerId"
        prop="tmptTimerId"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
              <el-input v-if="row.edit" v-model="row.tmptTimerId" class="edit-input" size="mini" />
              <span v-else>{{ row.tmptTimerId }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="删除标志"
        prop="deleteflag"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
              <select-option
                  v-if="row.edit"
                  v-model="row.deleteflag.id"
                  size="mini"
                  style="width: 100px; "
                  class="edit-input"
                  prop-name="deleteflag"
                  :prop-ds-type=1
              />
              <select-option
                  v-else
                  :disabled=true
                  v-model="row.deleteflag.id"
                  size="mini"
                  style="width: 100px; "
                  class="edit-input"
                  prop-name="deleteflag"
                  :prop-ds-type=1
              />
        </template>
      </el-table-column>-->

      <!--<el-table-column
        label="创建日期"
        prop="createdate"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
              <span>{{ row.createdate }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="修改日期"
        prop="modifydate"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
              <span>{{ row.modifydate }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="创建人"
        prop="createman"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
              <span>{{ row.createman }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="修改人"
        prop="modifyman"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
              <span>{{ row.modifyman }}</span>
        </template>
      </el-table-column>-->


      <!--操作Button + 页面级权限控制:hasPermission
      <el-table-column v-if="hasPermission(['tmptTimerLog:update','tmptTimerLog:delete'])" fixed="right" label="操作" align="center" min-width="180">
        <template slot-scope="{row,$index}">
          <el-button v-show="row.edit" type="success" icon="el-icon-close" title="取消" size="mini" @click="cancelEdit(row)"></el-button>
          <el-button v-if="row.edit" type="success" icon="el-icon-check" title="保存" size="mini" @click="confirmEdit(row)"></el-button>
          <el-button v-show="hasPermission(['tmptTimerLog:update'])" v-else type="primary" icon="el-icon-edit" title="编辑" size="mini" @click="row.edit=!row.edit">
          </el-button>
          <el-button v-show="hasPermission(['tmptTimerLog:delete'])" type="danger" icon="el-icon-delete" title="删除" size="mini" @click="handleDelete(row)">
          </el-button>
        </template>
      </el-table-column>-->
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <form-details ref="formDetails" :row="row" :isModule="true" @createResult="createResult"/>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {fetchList, updateApi, deleteApi} from './api'
import waves from '@/directive/waves' // waves directive
import { parseTime, reorgQueryParams, resizeTableHeight } from '@/utils'
import checkPermission from '@/utils/permission'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import FormDetails from './form-details.vue' // add form form dialog
// 从当前View的私有数据对象中取数据
import { pickerOptions, pickerOptionsSingleDate } from './data'
// 导入多选项组件
import SelectOption from '@/views/coding/components/SelectOption'

export default {
    name: 'TmptTimerLog-ListLineEdit',

    components: { Pagination, FormDetails, SelectOption },
    directives: { waves },

    props: {
        // 作为子组件时，需要回调传值；应用场景：一对多关联查询时，点击左边查询列表，传值给右边子列表，查询子列表结果
        isModule: {
            type: Boolean,
            default: false
        },
        // 当作为侧边查询结果显示的右子组件时，接收父组件的传值，watch中查询
        parentRow: Object
    },

    filters: {
        statusFilter(status) {
            const statusMap = {
                published: 'success',
                draft: 'info',
                deleted: 'danger'
            }
            return statusMap[status]
        },
        shortMsg(msg) {
            return msg.substr(0, 150)
        }
    },

    data() {
        return {
          tableKey: 0,
          list: [],
          total: 0,
          footer: [],
          listLoading: false,
          queryLoading: false,
          downloadLoading: false,
          listQuery: {
              page: 1,
              limit: 20
          },
          importanceOptions: [1, 2, 3],
          sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
          statusOptions: ['published', 'draft', 'deleted'],
          dialogFormVisible: false,
          dialogStatus: '',
          textMap: {
              update: '编辑',
              create: '新增'
          },
          downloadLoading: false,
          pickerOptions: pickerOptions,
          pickerOptionsSingleDate: pickerOptionsSingleDate,
          deleteflagList: [], // 多选项列表
          row: {},
          tableHeight:0, // 表格高度
          filterContainerHeight: 0, // 查询容器高度
          clientHeight: 0 // 浏览器高度
        }
    },
    watch: {
        // 当作为侧边查询的子组件时，接收父组件的传值，watch中查询
        parentRow(pRow) {
            this.listQuery[pRow.classInstance+'Id'] = pRow.id // parantId, 需修改成主表ID。******
            this.handleFilter()
        }
    },

    created() {
        this.getList()
    },

    mounted () {
        // 浏览器、元素大小变化时，动态调整table高度
        resizeTableHeight(this, 'filter-container-TmptTimerLog')
    },

    methods: {
        // 页面级权限控制，调用方法如：hasPermission(['a2user:delete'])
        hasPermission(needPermisions) {
          return checkPermission(needPermisions)
        },
        // 刷新
        getList() {
            this.queryLoading = true
            this.listLoading = true
            // 重组查询条件
            const params = Object.assign({}, this.listQuery)
            reorgQueryParams(params)
            // 查询
            fetchList(params).then(result => {
                if (!result.success) {
                    this.notify(result)
                    this.queryLoading = false
                    this.listLoading = false
                    return
                }
                const items = result.map.rows
                this.total = result.map.total
                // 备份数据，编辑还原用
                this.list = items.map(v => {
                    this.$set(v, 'edit', false) // https://vuejs.org/v2/guide/reactivity.html
                    v.original = Object.assign({}, v)
                    return v
                })
                // footer
                if (result.map.footer && result.map.footer.length>0) {
                  this.footer = result.map.footer
                }
                this.queryLoading = false
                this.listLoading = false
                ++this.tableKey
            })
        },
        // 从第一页开始查询
        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        // 排序
        sortChange(data) {
            const { prop, order } = data
            if (prop === 'id') {
                this.sortByID(order)
            }
        },
        sortByID(order) {
            if (order === 'ascending') {
                this.listQuery.sort = '+id'
            } else {
                this.listQuery.sort = '-id'
            }
            this.handleFilter()
        },
        // SUM
        getSummaries(param) {
            if (this.footer.length == 0) {
              return []
            }
            const sums = [];
            const { columns, data } = param;
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                if (this.footer[0][column.property]) {
                    sums[index] = this.footer[0][column.property]
                    return;
                }
            });
            return sums;
        },
        // download excel
        handleDownload() {
            // 重组查询条件
            const params = Object.assign({}, this.listQuery)
            params.page = 1
            params.limit = 10000000
            reorgQueryParams(params)
            console.log(params)
            // 查询
            this.downloadLoading = true
            fetchList(params).then(result => {
                if (!result.success) {
                    this.notify(result)
                    this.downloadLoading = false
                    return
                }
                import('@/vendor/Export2Excel').then(excel => {
                    const tHeader = ['Id', '名称', '创建时间', '创建人']  // excel中显示的列名
                    const filterVal = ['id', 'name', 'createdate', 'createman'] // excel中显示哪些列，与tHeader对应
                    const list = result.map.rows
                    const data = this.formatJson(filterVal, list)
                    excel.export_json_to_excel({
                        header: tHeader,
                        data,
                        filename: 'excel',
                        autoWidth: true,
                        bookType: 'xlsx'
                    })
                    this.downloadLoading = false
                })
            })
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => {
                if (j === 'timestamp') {
                    return parseTime(v[j])
                } else {
                    return v[j]
                }
            }))
        },
        // 添加操作 start
        handleCreate() {
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
            // 消除上次出现的验证信息
            this.$nextTick(() => {
                this.$refs['formDetails'].clearValidate()
                this.$refs['formDetails'].resetTemp()
                this.$refs['formDetails'].defaultTemp()
            })
        },
        // 调用子组件操作数据
        createData() {
            this.$refs['formDetails'].createData()
        },
        // 子组件操作成功，回调此方法，关闭弹框、刷新
        createResult() {
            this.dialogFormVisible = false
            this.handleFilter()
        },
        // 编辑操作 start
        cancelEdit(row) {
            // 还原原始值
            Object.keys(row).forEach(key => {
                if (key !== 'original' && key !== 'edit') {
                    row[key] = row.original[key]
                }
            })
            row.edit = false
            // row.original.edit = false
            this.$message({
                message: '数据恢复到原始值',
                type: 'warning'
            })
        },
        confirmEdit(row) {
            const param = Object.assign({}, row)
            param.original = {}
            updateApi(param).then((r) => {
                this.notify(r)
                if (r.success) {
                    row.edit = false
                    // 原始值：更新成最新输入值
                    Object.keys(row).forEach(key => {
                        if (key !== 'original' && key !== 'edit') {
                            row.original[key] = row[key]
                        }
                    })
                }
            })
        },
        // 删除操作
        handleDelete(row) {
            this.$confirm('确认删除吗？')
                .then(_ => {
                    // delete api
                    deleteApi({ id: '' + row.id }).then((r) => {
                        this.notify(r)
                        if (r.success) {
                            this.getList()
                        }
                    })
                    // end
                })
                .catch(_ => {})
        },
        // 行点击事件；应用场景：一对多关联查询时，点击左边查询列表，传值给右边子列表，查询子列表结果
        handleRowClick(row, column, event) {
            // 从父组件调用此方法，进行回调下
            if (this.isModule) {
              row.classInstance = 'tmptTimerLog'
              this.$emit('input', row)
            }
        },
        getSortClass: function(key) {
            const sort = this.listQuery.sort
            return sort === `+{key}` ? 'ascending' : 'descending'
        }
    }
}
</script>
<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 100px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 100%;
  }
</style>
